# 导入所需模块
import cv2 as cv2
import numpy as np
import imutils

# 打开摄像头
cap = cv2.VideoCapture(0)
height = 380
width = 640
def color (frame):
    # 读取每一帧
    # _, frame = cap.read()
    # # 重设图片尺寸以提高计算速度
    frame = imutils.resize(frame, height=380,width=640)
    # 进行高斯模糊
    blurred = cv2.GaussianBlur(frame, (11, 11), 0)
    # 转换颜色空间到HSV
    hsv = cv2.cvtColor(blurred, cv2.COLOR_BGR2HSV)
    # 定义红色无图的HSV阈值
    lower_red = np.array([35, 43, 46])
    upper_red = np.array([77, 255, 255])
    # 对图片进行二值化处理
    mask = cv2.inRange(hsv, lower_red, upper_red)
    # 腐蚀操作
    mask = cv2.erode(mask, None, iterations=2)
    # 膨胀操作，先腐蚀后膨胀以滤除噪声
    mask = cv2.dilate(mask, None, iterations=2)
    # cv2.imshow('mask', mask)
    # 寻找图中轮廓
    cnts = cv2.findContours(mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
    # 如果存在至少一个轮廓则进行如下操作
    if len(cnts) > 0:
        # 找到面积最大的轮廓
        c = max(cnts, key=cv2.contourArea)
        # 使用最小外接圆圈出面积最大的轮廓
        # ((x, y), radius) = cv2.minEnclosingCircle(c)
        # 计算轮廓的矩
        M = cv2.moments(c)
        # 计算轮廓的重心
        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))
        # 只处理尺寸足够大的轮廓
        # if radius > 5:
            # 画出最小外接圆
            # cv2.circle(frame, (int(x), int(y)), int(radius), (0, 255, 255), 2)
            # 画出重心
            # cv2.circle(frame, center, 5, (0, 0, 255), -1)
    else:center=[]
    return [frame,center]
def decide(width,centery):
    theta=(centery-width/2)/(width/2)*90
    return theta

if __name__ == '__main__':
    img = cv2.imread('C:/Users/blessing/Desktop/img/home/pi/Desktop/smart-car/img/green1.jpg')
    cv2.namedWindow('image', cv2.WINDOW_NORMAL)
    frame,center=color(img)
    print(center)
    if len(center) > 0:
        centery=center[0]
        theta=decide(width, centery)
        cv2.circle(frame, center, 5, (0, 0, 255), -1)
        cv2.line(frame, (centery,0), (centery, 100), (0, 255, 0),2)
        cv2.imshow('image', frame)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    else:theta=-180
    print(theta)